package com.yj.idempotence.dynamicDataSource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
@Slf4j
public class DynamicDataSourceConfig {



    @Bean
    @ConfigurationProperties("spring.datasource.dev")
    public DataSource devDataSource(){

        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.prod")
    public DataSource prodDataSource(){

        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/**.xml"));
        return sessionFactory.getObject();
    }

    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DynamicDataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean
    public DynamicDataSource dynamicDataSource(@Qualifier("devDataSource")DataSource devDataSource,@Qualifier("prodDataSource")DataSource prodDataSource){
        HashMap<Object, Object> map = new HashMap<>();
        map.put(DynamicDataSourceType.DEV_DATASOURCE,devDataSource);
        map.put(DynamicDataSourceType.PROD_DATASOURCE,prodDataSource);

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(map);
        dynamicDataSource.setDefaultTargetDataSource(devDataSource());

        return dynamicDataSource;
    }




}
